import { ISkerMaster } from "./types"
import { createStorage, getDeviceUuid, httpPost } from "./utils"

export abstract class Updater {
    constructor(public name: string, public master: ISkerMaster) { }
    update(): void {
        this.checkPackage(this.name)
    }
    log(msg: string) {
        this.master.update(msg)
    }
    tryPost(path: string, body: any, def: any = {}) {
        try {
            return httpPost(path, body, false)
        } catch (e) {
            console.error(`http post error: ` + e?.toString())
            this.log(`网络或服务器错误`)
            return def;
        }
    }
    private checkPackage(name: string) {
        const SD = files.getSdcardPath()
        const root = files.join(SD, 'sker');
        files.ensureDir(root)
        const downloadDir = files.join(root, 'downloads')
        files.ensureDir(downloadDir)

        const dirPath = files.join(root, `modules/`)
        files.ensureDir(dirPath)
        const packageInfo = this.tryPost('client/checkPackage', { name, uuid: getDeviceUuid() })
        const storage = createStorage()
        const version = storage.get(`${name}.version`)
        if (version !== packageInfo.version) {
            this.log(`最新版本：${packageInfo.version}`);
            sleep(1000)
            // 去下载地址下载
            const download = http.get(packageInfo.url) as AutoJs.Response;
            if (download.statusCode === 200) {
                const filePath = files.join(downloadDir, `${name}-${packageInfo.version}.zip`)
                files.createWithDirs(filePath)
                files.writeBytes(filePath, download.body.bytes())
                this.log(`下载完成,正在解压并安装...`)
                sleep(1000)
                const zipFile = $zip.open(filePath)
                if (!zipFile.isValidZipFile()) {
                    this.log(`更新失败, 无效zip文件`)
                    sleep(1000)
                    return;
                }
                if (zipFile.isEncrypted()) {
                    this.log(`更新失败, 文件已加密`)
                    sleep(1000)
                    return;
                }
                zipFile.extractAll(dirPath)
                sleep(1000)
                storage.put(`${name}.version`, packageInfo.version)
                sleep(1000)
                this.log(`更新并安装完成`);
                sleep(1000)
                return files.join(dirPath, name);
            }
            this.log(`更新失败`)
            sleep(1000)
        } else {
            this.log(`暂无更新`)
            sleep(1000)
            return files.join(dirPath, `${name}`);
        }
    }
}